package com.moyun.modelclass.utils;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;

import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * Created by duobao on 2018/3/19.
 */

public class RichEditor extends WebView {
	private String mContents;
	private static final String SETUP_HTML = "file:///android_asset/editor.html";
	private static final String CALLBACK_SCHEME = "re-callback://";
	private OnTextChangeListener mTextChangeListener;

	public RichEditor(Context context) {
		this(context, null);
	}

	public RichEditor(Context context, AttributeSet attributeSet) {
		this(context, attributeSet, 0);
	}

	public RichEditor(Context context, AttributeSet attributeSet, int i) {
		super(context, attributeSet, i);
		setVerticalScrollBarEnabled(false);
		setHorizontalScrollBarEnabled(false);
		getSettings().setJavaScriptEnabled(true);

		setWebViewClient(new EditorWebViewClient());

		loadUrl(SETUP_HTML);
	}

	public void setHtml(String content) {
		if (content == null) {
			content = "";
		}
		mContents = content;
		try {
			exec("javascript:setHtml('" + URLEncoder.encode(mContents, "UTF-8") + "');");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getHtml() {
		return mContents;
	}

	public void setOnTextChangeListener(OnTextChangeListener listener) {
		mTextChangeListener = listener;
	}

	/**
	 * 插入图片
	 *
	 * @param url
	 */
	public void insertImage(String url) {
		exec("javascript:insertImage('" + url + "');");
	}

	protected void exec(final String trigger) {
		load(trigger);
	}

	private void load(String trigger) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			evaluateJavascript(trigger, null);
		} else {
			loadUrl(trigger);
		}
	}

	private void callback(String text) {
		mContents = text.replaceFirst(CALLBACK_SCHEME, "");
		if (mTextChangeListener != null) {
			mTextChangeListener.onTextChange(mContents);
		}
	}


	public interface OnTextChangeListener {

		void onTextChange(String text);
	}

	protected class EditorWebViewClient extends WebViewClient {
		@Override
		public void onPageFinished(WebView webView, String s) {
			super.onPageFinished(webView, s);
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView webView, String s) {
			String decode;
			try {
				decode = URLDecoder.decode(s, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// No handling
				return false;
			}

			if (TextUtils.indexOf(s, CALLBACK_SCHEME) == 0) {
				Log.e("接受到回调:", decode);
				callback(decode);
				return true;
			}
			return super.shouldOverrideUrlLoading(webView, s);
		}
	}
}
